package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2021-11-02
 */
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {

    //根据名称模糊查询分页列表
    @Override
    public ResponseResult listByName(ChannelDto dto) {
        // 构建查询条件
        LambdaQueryWrapper<WmChannel> qw = new LambdaQueryWrapper<>();
        // 判断传入的频道名称是否为空,不为空的话添加查询条件
        if (!StringUtils.isEmpty(dto.getName())) {
            qw.like(WmChannel::getName, dto.getName());
        }
        //创建分页条件
        IPage<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmChannel> iPage = this.page(page, qw);
        // 给前端返回通用的分页响应
        return new PageResponseResult(
                dto.getPage(),
                dto.getSize(),
                iPage.getTotal(),
                iPage.getRecords()
        );
    }

    //新增频道
    @Override
    public ResponseResult saveChannel(WmChannel channel) {
        // 保存新的频道,判断频道名称是否已经存在,已经存在不再新增
        //检查参数
        if (channel == null || StringUtils.isEmpty(channel.getName())) {
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据频道名称查询记录
        LambdaQueryWrapper<WmChannel> qw = new LambdaQueryWrapper<>();
        qw.eq(WmChannel::getName, channel.getName());
        int count = this.count(qw);
        //如果数据存在，提示用户该数据已存在
        if (count > 0) {
            return ResponseResult.okResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //数据不存在，进行保存
        //添加当前时间
        channel.setCreatedTime(new Date());
        boolean save = this.save(channel);
        if (save) {
            return ResponseResult.okResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        return ResponseResult.okResult(channel.getId());
    }
}























